/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: SysUserController.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2015年1月20日
 */
package com.sirdc.modules.sys.web;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sirdc.modules.core.entity.StringEntity;
import com.sirdc.modules.core.exceptions.UserExistException;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.util.PasswordHelper;
import com.sirdc.modules.sys.util.SysUserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sirdc.modules.core.exceptions.ServiceException;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.UserUtils;
import com.sirdc.modules.utils.StringUtils;

/**
 * 系统用户表维护
 *
 * @version Revision: 0.0.1
 * @author: huiyang.yu
 * @Date: 2015年1月20日
 */
@Controller
@RequestMapping(value = "/modules/sys/user")
public class SysUserController extends JsonBaseController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private PasswordHelper passwordHelper;
    @Autowired
    private SysLoginService sysLoginService;

    @Override
    protected String getView(String view) {
        return "/modules/sys/user/" + view;
    }

    /**
     * 初始化用户表列表界面
     *
     * @return url
     */
    @RequiresPermissions("modules:sys:user:query")
    @RequestMapping(method = RequestMethod.GET)
    public String initPage() {
        return getView("query");
    }

    /**
     * 输出json用户表
     *
     * @param filter
     * @return json
     */
    @ResponseBody
    @RequiresPermissions("modules:sys:user:query")
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute SysUserFilter filter) {
        List<SysUserDataBean> sysUserDataBeans = sysUserService.queryOnDatabean(filter);
        return coverJqGrid(filter, sysUserDataBeans);
    }

    /**
     * 跳转至filter界面
     *
     * @param filter
     * @return
     */
    @RequestMapping("/filter")
    @RequiresPermissions("modules:sys:user:query")
    public String filter(@ModelAttribute SysUserFilter filter,Model model) {
        List<SysDept> bookLists=new ArrayList<>();
        List<SysDept> depts = deptService.queryByDeptLevel(3);
        List<SysDept> dcDepts = deptService.queryDeptList("/01/");
        bookLists.addAll(dcDepts);
        bookLists.addAll(depts);
        model.addAttribute("bookLists",bookLists );
        return getView("filter");
    }

    /**
     * 创建用户表字段
     *
     * @return
     */
    @ResponseBody
    @RequiresPermissions("modules:sys:user:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute SysUserDataBean datebean) {
        try {
            //密码策略
            String reg ="^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$" ;
            //密码正则表达式

            String password = datebean.getPassword();

            if (!password.matches(reg)) {
                return coverMessage("500","提交失败：至少8个字符，至少1个大写字母，1个小写字母和1个数字");
            }

            sysUserService.saveUserLogin(datebean);
        } catch (UserExistException ue) {
            return coverMessage("500", "用户名已存在");
        } catch (Exception e) {
            throw e;
        }
        return coverMessage("200");
    }
//测试git

    /**
     * 初始化创建用户表界面
     *
     * @param model
     * @return url
     */
    @RequiresPermissions("modules:sys:user:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showAddView(@ModelAttribute SysUserDataBean datebean, Model model) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
        List<SysDept> depts = sysDeptService.query();
        datebean = new SysUserDataBean();
        model.addAttribute("datebean", datebean);
        model.addAttribute("depts", depts);
        return getView("form");
    }

    /**
     * 初始化更新用户表界面
     *
     * @param model
     * @param id
     * @return url
     */
    @RequiresPermissions("modules:sys:user:edit")
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEditView(Model model, @PathVariable String id) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
        List<SysDept> depts = sysDeptService.query();
        SysUserDataBean datebean = sysUserService.getUserDataBeanById(id);
        model.addAttribute("datebean", datebean);
        model.addAttribute("depts", depts);
        return getView("form");
    }

    /**
     * 更新用户表操作
     *
     * @return
     */
    @ResponseBody
    @RequiresPermissions("modules:sys:user:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute SysUserDataBean datebean) {
        if (StringUtils.isNotBlank(SysUserUtils.getUserId())) {
            sysUserService.updateUserLogin(datebean);
            return coverMessage("200");
        }else{
            return coverMessage("500");
        }
    }

    /**
     * 查询用户表并跳转至详情界面
     *
     * @param id
     * @param model
     * @return url
     */
    @RequiresPermissions("modules:sys:user:detail")
    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable String id, Model model) {
        SysUser sysUser = sysUserService.getById(id);

        if (sysUser == null) {
            throw new ServiceException("message");
        }

        model.addAttribute("sysUser", sysUser);
        return getView("detail");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequiresPermissions("modules:sys:user:delete")
    @RequestMapping(value = "/delete/{id}")
    public Message delete(@PathVariable List<String> id) {
        boolean del = id.remove(UserUtils.getUserId());
        sysUserService.batchDelete(id);
        if (del) {
            return coverMessage("500", "删除成功，但您不能删除自己");
        }
        return coverMessage("200");
    }

    /**
     * 获取个人基本资料
     *
     * @return
     */
    @RequestMapping(value = "/profile")
    public String profile(Model model) {
        String userId = UserUtils.getUserId();
        SysUser user = sysUserService.getById(userId);
        model.addAttribute("user", user);
        return getView("profile");
    }

    /**
     * 保存 个人基本资料
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveProfile")
    public Message saveProfile(@ModelAttribute SysUser user) {
        SysUser sysUser = sysUserService.getById(user.getSysId());
        sysUser.setMobile(user.getMobile());
        sysUser.setName(user.getName());
        sysUserService.update(sysUser);
        return coverMessage("200");
    }

    /**
     * 显示修改用户个人密码界面
     *
     * @return
     */
    @RequestMapping(value = "/showChangePassView")
    public String showChangePassView(Model model) {
        return getView("changePass");
    }

    /**
     * 修改用户密码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changePass")
    public Message changePass(@ModelAttribute SysUserDataBean databean) {
        if (StringUtils.isEmpty(databean.getPassword()) || StringUtils.isEmpty(databean.getOldPassword())) {
            return coverMessage("500", "请输入完整的信息");
        }
        String userId = UserUtils.getUserId();
        SysLogin login = sysUserService.getSysLoginById(userId);
        String encryptPass = sysUserService.getEncryPass(databean.getOldPassword(), login.getSaltKey());
        if (login.getPassword().equals(encryptPass)) {
            databean.setUserId(userId);
            sysUserService.updatePassword(databean);
            return coverMessage("200");
        }
        return coverMessage("500", "对不起，您当前输入的旧密码有误");
    }

    /**
     * 补全必填信息
     *
     * @param bean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateMust", method = RequestMethod.POST)
    public Message updateMust(SysUserDataBean bean) {
        //查询当前用户
        String userId = SysUserUtils.getUserId();
        SysUser user = sysUserService.getById(userId);
        SysLogin login = sysUserService.getSysLoginById(userId);
        if (StringUtils.isNotBlank(bean.getPassword())) {
            if ("123456".equals(bean.getPassword())){
                return coverMessage("500","密码过于简单");
            }
            //更改密码
            login.setPassword(bean.getPassword());
            //加密密码
            passwordHelper.encryptPassword(login);
            //更新
            sysLoginService.update(login);
        }
        if (StringUtils.isNotBlank(bean.getMobile())) {
//            if (isMobile(bean.getMobile())){
                user.setMobile(bean.getMobile());
                sysUserService.update(user);
//            }return coverMessage("500","手机号格式错误");
        }

        if (StringUtils.isBlank(user.getMobile())) {
            return coverMessage("500","请输入手机号");
        }
        return coverMessage("200");
    }

  /**
   * 手机号验证
   *
   * @param  str
   * @return 验证通过返回true
   */
  public static boolean isMobile(String str) {
      Pattern p = null;
      Matcher m = null;
      boolean b = false;
      p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$"); // 验证手机号
      m = p.matcher(str);
      b = m.matches();
      return b;
  }
}